package com.ch03.file;

import java.io.*;
import java.util.*;

public class StockFileReader {
	
	public static final int FILEFORMATLENGTH = 2;
	private ArrayList<String> fileRead_ErrorList;
	private String[][] stockData;
	
	public StockFileReader()
	{
		stockData = new String[10][2];
		fileRead_ErrorList = new ArrayList<String>(50);
	}
	
	public ArrayList<String> getFileReadErrorList()
	{
		return fileRead_ErrorList;
	}
	
	public void setFileReadErrorList(ArrayList<String> errList)
	{
		fileRead_ErrorList = errList;
	}

	public static void main(String[] args) {
		StockFileReader reader = new StockFileReader();
		System.out.println(args[0]);
		reader.readFile(args[0]);

	}
	
	public void readFile(String filename)
	{
		File inputfile = new File(filename);
		String line = null;
		String[] splitLine = null;
		int x = 0;
		ArrayList lines = new ArrayList();
			
		if (! inputfile.exists())
		{
				System.out.println("Input file not found");
				System.exit(0);
		}
		else 
		{
			try 
			{
				BufferedReader buf = new BufferedReader(new FileReader(inputfile));
				line = buf.readLine();
				do
				{
					if  (line.equals(""))
					{
						fileRead_ErrorList.add("Blank line while reading input file");
					} else {
					splitLine = line.split(",");
				
				// check if the line has 2 tokens
					if (splitLine.length == FILEFORMATLENGTH)
					{
						if ((splitLine[0] != null) && (splitLine[1] != null))
						{
					   	   lines.add(splitLine[0] + "," + splitLine[1]);
						} else
						{
							fileRead_ErrorList.add(line + "  One of the tokens is null");
													}
					} else
					{
						fileRead_ErrorList.add(line + "  Does not have two tokens");
					   
					}
					}
				} while ((line = buf.readLine()) != null);
			} catch (IOException exception)
			{
				System.out.println(exception.getMessage());
			}
			
			try
			{
				StockDBWriter dbWriter = new StockDBWriter();
				dbWriter.updateDB(lines);
			  //  dbWriter.updateDB(splitLine);
			}
			catch (Exception exception)
			{
			    fileRead_ErrorList.add(exception.getMessage());
			}
			
			System.out.println("List of errors in reading and updating the file to databases");
			for (String s : fileRead_ErrorList)
			{
				System.out.println(s);
			}
		}
	}
}

	


